package com.it.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.reggie.common.BaseContext;
import com.it.reggie.common.CustomException;
import com.it.reggie.entity.*;
import com.it.reggie.mapper.OrderMapper;
import com.it.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService; // 购物车数据

    @Autowired
    private UserService userService; // 用户信息

    @Autowired
    private AddressBookService addressBookService; // 地址

    @Autowired
    private OrderDetailService orderDetailService; // 订单明细

    /**
     * 用户下单
     * @param orders
     */
    @Override
    @Transactional // 事务，操作两张表时候，为了保证数据的一致性
    public void submit(Orders orders) {
        // 获取当前用户的ID
        Long userId = BaseContext.getCurrentId();

        // 查询当前用户的购物车数据
        // 条件构造器
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        // SQL: seclect * from ShoppingCart where userId = ?
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);

        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new CustomException("购物车为空，不能下单");
        }

        // 查询用户信息
        User user = userService.getById(userId);

        // 查询地址信息
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            throw new CustomException("用户地址信息有误，不能下单");
        }


        // 调用MP的IdWorker.getId()方法，随机生成订单号
        long orderId = IdWorker.getId();

        // 计算总金额    将订单明细封装为一个List集合
        // AtomicInteger原子操作（在多线程里用比较好，使用int.double在多线程的情况下可能会计算错误），将订单里菜品以及套餐的金额累加到amount里
        AtomicInteger amount = new AtomicInteger(0);

        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);  // 订单号
            orderDetail.setNumber(item.getNumber()); // 订单分数
            orderDetail.setDishFlavor(item.getDishFlavor()); // 口味
            orderDetail.setDishId(item.getDishId()); // 菜品ID
            orderDetail.setSetmealId(item.getSetmealId()); // 套餐Id
            orderDetail.setName(item.getName());  // 菜品名称或者是套餐名称
            orderDetail.setImage(item.getImage()); // 菜品图片或者套餐图片
            orderDetail.setAmount(item.getAmount()); // 当前金额 单一份的金额，不是订单总金额
            // 计算订单总金额（getAmount单一份的金额，multiply乘以 BigDecimal（将number进行了封装）（getNumber份数） ）
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        // 向订单表插入数据，一条数据


        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        // 向订单明细表插入数据，多条数据(saveBatch批量写入多条数据)
        orderDetailService.saveBatch(orderDetails);
        // 下单成功，清空购物车数据
        shoppingCartService.remove(queryWrapper);
    }
}
